﻿using System;
using System. Collections. Generic;
using System. Windows;
using System. Windows. Data;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using Microsoft. Phone. Shell;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using WP7_WebLib. HttpPost;
using NextApp. WP7. Util;
using NextApp. WP7. Cache. NextApp;

namespace NextApp. WP7. View
{
    public partial class AddComment : PhoneApplicationPage
    {
        #region Initialize
        public AddComment( )
        {
            InitializeComponent( );
			this. PrepareToOrientation( );
            this. ApplicationTitle. Text = Config. Instance. blog_title;
            this. Loaded += new RoutedEventHandler(AddComment_Loaded);
            //显示发表评论的上次使用过的用户名 邮箱 以及网址
            this. Loaded += (s, e) =>
                {
                    this. txt_UserName. Text = Config. Instance. Comment_UserName;
                    this. txt_Email. Text = Config. Instance. Comment_Email;
                    if ( this.txt_Email.Text.IsNotNullOrWhitespace() )
                    {
                        this. txt_Email. Watermark = string. Empty;
                    }
                    this. txt_Url. Text = Config. Instance. Comment_Website;
                };
        }
        /// <summary>
        /// 该对平对应的文章ID
        /// </summary>
        private int postID { get; set; }
        protected override void OnNavigatedTo(System. Windows. Navigation. NavigationEventArgs e)
        {
            Util. Tool. CheckAppBar(this);
            if ( this.NavigationContext.QueryString.ContainsKey("post") )
            {
                this. postID = this. NavigationContext. QueryString[ "post" ]. ToString( ). ToInt32( );
            }
            base. OnNavigatedTo(e);
        }

        #endregion

        #region 发表评论相关方法
        private void btn_Comment_Pub_Click(object sender, RoutedEventArgs e)
        {
            if ( NextAppSingleton.Instance.IsReady == false )
            {
                MessageBox. Show("网络还未加载完毕");
                return;
            }
            //保存发表评论的信息
            this. SaveCommentInfo( );
            //准备发表评论的参数
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"post", this. postID},
                {"name", txt_UserName.Text},
                {"email", txt_Email.Text},
                {"url", txt_Url.Text},
                {"body", txt_Body.Text},
            };
            PostClient client = new PostClient(parameters) { UserAgent = Config. Instance. Http_User_Agent };
            client. DownloadStringCompleted += (s, e1) =>
            {
                if ( e1. Error != null )
                {
                    MessageBox. Show("添加评论失败", "网络错误", MessageBoxButton. OK);
                    return;
                }
				XElement x;
				try
				{
					x = XElement. Parse(e1. Result). Element("result");
				}
				catch ( Exception )
				{
					return;
				}
                ApiError _error = new ApiError
                {
                    errorCode = x. Element("errorCode"). Value. ToInt32( ),
                    errorMessage = x. Element("errorMessage"). Value,
                };
                this. ProgressIndicatorIsVisible = false;
                //分析错误代码
                this. DisplayResult_AddComment(_error);
            };
            if ( NextAppSingleton.Instance.url_comment_pub.IsNotNullOrWhitespace() )
            {
                client. DownloadStringAsync(new Uri(Config. Instance. GetApi(NextAppSingleton. Instance. url_comment_pub), UriKind. Absolute));
                this. ProgressIndicatorIsVisible = true;
            }
        }

        private void DisplayResult_AddComment( ApiError _error )
        {
            switch ( _error.errorCode )
            {
                case 1:
                    if ( MessageBox.Show("评论成功, 需要返回前一页吗?", "评论成功", MessageBoxButton.OKCancel) == MessageBoxResult.OK )
                    {
                        if ( this. NavigationService. CanGoBack )
                        {
                            this. NavigationService. GoBack( );
                        }
                        //跳转回文章页的 评论Pivot
                        //( Application. Current. RootVisual as PhoneApplicationFrame ). Navigate(new Uri(string. Format("/View/PostDetail.xaml?post={0}&portal=Comments", this. postID), UriKind. Relative));
                    }
                    break;
                case -1:
                    MessageBox. Show("评论失败, 其他错误");
                    break;
                case -2:
                    MessageBox. Show("评论失败, 没有评论权限");
                    break;
                default:
                    MessageBox. Show(_error. errorMessage);
                    break;
            }
        }

        /// <summary>
        /// 保存发表评论的信息
        /// </summary>
        private void SaveCommentInfo( )
        {
            Config. Instance. Comment_UserName = this. txt_UserName. Text. Trim( );
            Config. Instance. Comment_Email = this. txt_Email. Text. Trim( );
            Config. Instance. Comment_Website = this. txt_Url. Text. Trim( );
        }
        #endregion

        #region 进度条处理
        void AddComment_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray. ProgressIndicator = new ProgressIndicator( );
            SystemTray. ProgressIndicator. Text = "正在发表";
            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData. Source = this;
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsVisibleProperty, bindingData);
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsIndeterminateProperty, bindingData);
        }
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty. Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(AddComment),
            new PropertyMetadata(false));
        public bool ProgressIndicatorIsVisible
        {
            get { return ( bool )GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }

        #endregion

        #region 登入注销处理
        //登入
        private void menuItem_Login_Click(object sender, EventArgs e)
        {
            Util. Tool. Login( );
        }

        //注销
        private void menuItem_Logout_Click(object sender, EventArgs e)
        {
            Util. Tool. Logout( );
            Util. Tool. CheckAppBar(this);
        }
        #endregion
    }
}